#!/usr/bin/perl -w
use Config::Simple;
use Processor;
use Process;
use Switch;
use Tupla;

package ConfigManager;
sub new
{
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub getConfig {
	my( $self ) = @_;
	my $cfg = new Config::Simple('conf/sim.conf');
	my $proc = new Processor();
	
	$proc->setProcessAlgorithm($cfg->param("ProcessAlgorithm"));
	$proc->setQuantum($cfg->param("Quantum"));
	$proc->setThreadAlgorithm($cfg->param("ThreadAlgorithm"));
	$proc->setThreadQuantum($cfg->param("ThreadQuantum"));
	$proc->setKernels($cfg->param("Kernels"));

	return $proc;	
}

sub getProcesses{
	my( $self ) = @_;
	my $cfg = new Config::Simple('conf/processes');
	
	my @processesLst = ();
	
	for( $a = 0; $a < 10; $a += 1 ){ #max 10 procesos
    	my $procNumber = "p".$a;
    	my $firstThred = $procNumber."_k1";
    	my $firstUlt = $firstThred."_u1"; 
    	if((defined($cfg->param($firstThred)) && $cfg->param($firstThred) ne "") || (defined($cfg->param($firstUlt)) && $cfg->param($firstUlt) ne "")){
	    	my $procThread = "";
	    	for($j=1; $j<4; $j++){ #max 3 klts
		    	$procThread = $procNumber."_k".$j;
		    	my $thread = new Process();
		    	my $validThread = 0;
	    		$thread->setStartTime($cfg->param($procNumber."_t0"));
	    		$thread->setName($procThread);
	    	 
		    	if(defined($cfg->param($procThread)) && $cfg->param($procThread) ne ""){
			    	my @bursts;
			    	@bursts = _getBursts($cfg->param($procThread));
			    	$thread->setBursts(\@bursts);
			    	$validThread = 1;
		    	}
		    	
		    	my @procUlts;
		    	for($i=1;$i<4;$i++){ #max 3 ults
		    		my $ultName = $procThread."_u".$i;
		    		my $ultName2 = $procNumber."_u".$i;
		    		my $ult = new Process();
		    		$ult->setStartTime($cfg->param($ultName."_t0"));
		    		$ult->setName($ultName2); 
			    	if(defined($cfg->param($ultName)) && $cfg->param($ultName) ne ""){
				    	my @bursts;
				    	@bursts = _getBursts($cfg->param($ultName));
				    	$ult->setBursts(\@bursts);
				    	push @procUlts, $ult;
				    	$validThread = 1;
			    	}
		    	} 
		    	if(@procUlts){
			    	push $thread->{_ultsNew}, @procUlts;
		    	}
		    	if($validThread){
			    	push @processesLst, $thread;
		    	}
	    	}
    	}
	}
	
	my @sortedLst = sort { $a->getStartTime() cmp $b->getStartTime() } @processesLst;
	
	return @sortedLst;
}

sub _getThreads{
	my($procName) = @_;
	
	
}

sub _getBursts{
	my( $list ) = @_;
	#creo lista cpu io1 io2 io3
	my @lst = split(',', $list);
	my @retList = ();
	
	foreach(@lst){
		my @line = split('=', $_);
		my $burstLine = new Tupla($line[0], $line[1]);
		
		push @retList, $burstLine;
	}
	
	return @retList;
}
1;